package system_configuration_dao

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	"time"
)

func (cls *SystemConfiguration) SaveSystemConfiguration(ctx context.Context, systemConfiguration *model.SystemConfiguration) errors.Error {
	if nil == systemConfiguration {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSC_ON.SC_ON.SSC_ON.150357 systemConfiguration is nil")

		return errors.ErrorServerInternalError("IDSC_ON.SC_ON.SSC_ON.170357", "异常的传入参数")
	}

	systemConfiguration.UpdateTime = pointer.New(time.Now().Unix())
	if nil == systemConfiguration.CreateTime || 0 == *systemConfiguration.CreateTime {
		systemConfiguration.CreateTime = pointer.New(time.Now().Unix())

		if err := cls.GetDb(ctx).Model(new(model.SystemConfiguration)).Create(&systemConfiguration).Error; nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSC_ON.SC_ON.SSC_ON.250357 create systemConfiguration failed, err %v", err)

			return errors.ErrorServerInternalError("IDSC_ON.SC_ON.SSC_ON.270357", "创建数据失败")
		}

		return nil
	}

	if err := cls.GetDb(ctx).Model(new(model.SystemConfiguration)).Where("id = ?", systemConfiguration.Id).Updates(&systemConfiguration).Error; nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDSC_ON.SC_ON.SSC_ON.340357 save systemConfiguration failed, err %v", err)

		return errors.ErrorServerInternalError("IDSC_ON.SC_ON.SSC_ON.360357", "更新数据失败")
	}

	return nil
}
